package com.saxon.blog.shiro;

import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


import java.util.IdentityHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    @Bean
    public Realm realm () {
        return new RealmConfig ();
    }

    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager (@Qualifier ("realm") Realm realm,@Qualifier("defaultWebSessionManager") DefaultWebSessionManager defaultWebSessionManager) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager ();
        defaultWebSecurityManager.setRealm (realm);
        defaultWebSecurityManager.setSessionManager (defaultWebSessionManager);
        return defaultWebSecurityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean (@Qualifier ("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean ();
        shiroFilterFactoryBean.setSecurityManager (defaultWebSecurityManager);
        //设置权限登录
        shiroFilterFactoryBean.setLoginUrl ("/tologin");
        shiroFilterFactoryBean.setUnauthorizedUrl ("/Unauthorized");
        //设置需要的权限
        Map<String, String> filterChainDefinitionMap = new IdentityHashMap<> ();
        filterChainDefinitionMap.put ("/admin/*","perms[1]");
        filterChainDefinitionMap.put ("/admin/page/*","perms[1]");
        filterChainDefinitionMap.put ("/admin/*/*/*","perms[1]");
        shiroFilterFactoryBean.setFilterChainDefinitionMap (filterChainDefinitionMap);
        //
        return shiroFilterFactoryBean;
    }
    //去除第一次的jsession
    @Bean
   public DefaultWebSessionManager defaultWebSessionManager(){
        DefaultWebSessionManager defaultWebSessionManager = new DefaultWebSessionManager ();
        defaultWebSessionManager.setSessionIdUrlRewritingEnabled (false);
        return defaultWebSessionManager;
    }

}
